<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JAJX JSON请求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <div id="result"></div>
    <script>
        //获取元素对象
        const result = document.getElementById('result');
        //绑定事件
        document.addEventListener('keydown', function () {
            //1. 创建对象
            const xhr = new XMLHttpRequest();
            //设置响应体数据的类型
            xhr.responseType = 'json';
            //2. 初始化 设置请求方法和url
            xhr.open('GET', 'http://127.0.0.1:8092/json-server');
            //3. 发送
            xhr.send();
            //4. 事件绑定
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        // result.innerHTML = xhr.response;
                        //手动对数据转换
                        // let data = JSON.parse(xhr.response);
                        // console.log(data)
                        // result.innerHTML = data.name;
                        //自动转换
                        console.log(xhr.response)
                        result.innerHTML = xhr.response.name;
                    }
                }
            }
        })
    </script>
</body>

</html>